package com.dream.oauth2.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class CustomOAuth2UserService extends DefaultOAuth2UserService {

    @Override
    public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
        String registrationId = userRequest.getClientRegistration().getRegistrationId();
        log.info("处理OAuth2登录请求，提供商：{}", registrationId);
        
        if ("qq".equals(registrationId)) {
            // 从additionalParameters中获取openid和nickname
            String openid = (String) userRequest.getAdditionalParameters().get("openid");
            String nickname = (String) userRequest.getAdditionalParameters().get("nickname");
            String avatar = (String) userRequest.getAdditionalParameters().get("figureurl_qq_2");
            
            if (openid == null || openid.isEmpty()) {
                throw new OAuth2AuthenticationException("QQ openid不能为空");
            }
            
            // 构建用户属性
            Map<String, Object> attributes = new HashMap<>();
            attributes.put("openid", openid);
            if (nickname != null && !nickname.isEmpty()) {
                attributes.put("nickname", nickname);
            }
            if (avatar != null && !avatar.isEmpty()) {
                attributes.put("figureurl_qq_2", avatar);
            }
            
            log.info("构建QQ OAuth2User完成，openid: {}, nickname: {}, avatar: {}", openid, nickname, avatar);
            
            return new DefaultOAuth2User(
                Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
                attributes,
                "openid"  // 使用openid作为name属性
            );
        }
        
        // 其他提供商使用默认处理
        return super.loadUser(userRequest);
    }
}